package com.itany;

import redis.clients.jedis.Jedis;

public class RedisDemo2 {


    private  static long waitTimeOut=10000;
    private static Integer timeOut=10000;
    private static  String LOCK_SUCCESS="OK";


    /**
     * 获取分布式锁
     * @return
     */
    public  static boolean getRedisLock(String lockName,String requestId){
        try {
            Jedis jedis = new Jedis("127.0.0.1",6379);
            Long endTime = System.currentTimeMillis()+waitTimeOut;
            while (System.currentTimeMillis()<endTime){
                    String result=jedis.set(lockName,requestId,"NX","PX",timeOut);
                     if(LOCK_SUCCESS.equals(result)){
                         return  true;
                     }

                }

        }catch (Exception e){
            e.printStackTrace();
        }
        return  false;
    }



    /**
     * 释放分布式锁方法
     */
    public static void unRedisLock(String lockName,String requestId){
        //声明jedis对象
        Jedis jedis = new Jedis("127.0.0.1",6379);
        try {
              if (jedis.get(lockName).equals(requestId)){
                  jedis.del(lockName);
              }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        for(int i=0;i<3;i++){
            Thread td= new Thread(new Test());
            td.setName("Test"+i);
            td.start();
        }
    }

}
